package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.domain.ResponseResult;

import org.example.domain.dto.UserListDto;
import org.example.domain.dto.insertUserDto;
import org.example.domain.entity.User;
import org.example.domain.entity.UserRole;
import org.example.enums.AppHttpCodeEnum;
import org.example.exception.SystemException;
import org.example.service.UserRoleService;
import org.example.service.UserService;
import org.example.utils.BeanCopyUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {


    private final UserService userService;

    private final PasswordEncoder passwordEncoder;

    private final UserRoleService userRoleService;

    @PostMapping("/userList")
    public ResponseResult userList(@RequestBody UserListDto userListDto){

        System.out.println("----"+userListDto.getPageNum()+"---------");
        return userService.userList(userListDto);
    }


    @PutMapping("/changeUserStatus")
    public ResponseResult changeUserStatus(@RequestBody User user){

        return ResponseResult.okResult(userService.changeUserStatus(user));
    }

    @PostMapping("/addUser")
    public ResponseResult addUser(@RequestBody insertUserDto insertUserDto){
        User user = BeanCopyUtils.copyBean(insertUserDto, User.class);
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_ERROR);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_ERROR);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_ERROR);
        }
        String EncoderPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(EncoderPassword);
        userService.save(user);
        Integer userId = user.getId();
        Integer[] rolesId = insertUserDto.getRolesId();
        List<UserRole> userRoleList = new ArrayList<>();
        for(int i=0;i<rolesId.length;i++){
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(rolesId[i]);
            userRoleList.add(userRole);
        }

        return ResponseResult.okResult(userRoleService.saveBatch(userRoleList));
    }

    @PutMapping("/updateUser")
    public ResponseResult updateUser(@RequestBody insertUserDto insertUserDto){
        User user = BeanCopyUtils.copyBean(insertUserDto, User.class);
        userService.updateUser(user);
        userRoleService.deleteByUserId(user.getId());
        userRoleService.addUserRole(insertUserDto);
        return ResponseResult.okResult("更新成功");
    }
}
